const connection = require('../app/database');

class LabelService {
  async create(user_id,date,address,remark) {
    const statement = `INSERT INTO order_table (user_id,date,address,remark) VALUES (?,?,?,?);`;
    const [result] = await connection.execute(statement, [user_id,date,address,remark]);
    console.log(result)
    return result.insertId;
  }

  async addGood(order_id, product_id, count) {
    const statement = `INSERT INTO moment_order (order_id, moment_id, count) VALUES (?,?,?);`;
    const [result] = await connection.execute(statement, [order_id, product_id, count]);
    return result;
  }

  async getLabelByName(name) {
    const statement = `SELECT * FROM label WHERE name = ?;`;
    const [result] = await connection.execute(statement, [name]);
    return result[0];
  }

  async getLabels(userId,limit, offset) {
    const statement =
      `SELECT ot.id, ot.date, ot.status,
         JSON_ARRAYAGG(
             JSON_OBJECT('id', m.id, 'name', m.name, 'price', m.price, 'date', m.date, 'type', m.type, 'platform', m.platform)
         ) goods
        FROM order_table ot
        LEFT JOIN moment_order mo ON ot.id = mo.order_id
        LEFT JOIN moment m ON m.id = mo.moment_id
        WHERE ot.user_id = ?
        GROUP BY ot.id, ot.date, ot.status
        LIMIT ?, ?;
        `;

    const [result] = await connection.execute(statement, [userId,offset, limit]);
    return result;
  }
  async remove(orderId) {
    const statement = `DELETE FROM order_table WHERE id = ?`;
    const [result] = await connection.execute(statement, [orderId]);
    return result;
  }

}


module.exports = new LabelService();
